package org.kolonitsky.translator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static org.kolonitsky.translator.Settings.ENCODING;

/**
 * @author Alex.Kolonitsky
 */

public class GoogleTranslator extends ServiceTranslator {

    protected static final Log LOG = LogFactory.getLog(Translator.class);

    private static final String V2_URL = "https://www.googleapis.com/language/translate/v2?key=" + Settings.GOOGLE_KEY + "source=%s&target=%s&q=";

    private final Pattern chunkPattern;

    public GoogleTranslator(Lang to) {
    	this(to, DEFAULT_LIMIT);
    }

    public GoogleTranslator(Lang from, Lang to) {
    	this(from, to, DEFAULT_LIMIT);
    }

    public GoogleTranslator(Lang to, int limit) {
        this(Lang.DEFAULT, to, limit);
    }

    public GoogleTranslator(Lang from, Lang to, int limit) {
        super(from, to, limit);

        this.chunkPattern = Pattern.compile("(.{1," + limit + "})[.;:,\\s]|$");
    }

    protected String translateChunk(String text) {

		text = send(text);
        if (text == null) {
            return null;
        }

        JSONObject json = null;
        try {
            json = (JSONObject) new JSONParser().parse(text);
        } catch (ParseException e) {
            e.printStackTrace();  // TODO
        }

        if (json == null) {
            return null;
        }

        Map data = (Map) json.get("data");
        if (data == null) {
            return null;
        }

        List translations = (List) data.get("translations");
        if (translations == null || translations.size() == 0) {
            return null;
        }

        Map o = (Map) translations.get(0);
        if (o == null) {
            return null;
        }

        return (String) o.get("translatedText");
    }

    protected URL getUrl(String text) throws MalformedURLException, UnsupportedEncodingException {
        return new URL(String.format(V2_URL, from(), to()) + URLEncoder.encode(text, ENCODING));
    }

/*
    TODO
    protected ArrayList<String> chunkText(String text) {
        Matcher matcher = chunkPattern.matcher(text);

        ArrayList<String> res = new ArrayList<String>(text.length()/limit + 1);
        while (matcher.find()) {
            res.add(matcher.group(1));
        }

        return res;
    }
*/
}
